<?php
class Roles
{
	private static $_instance = null;
	private $_db = null;
	
	private function __construct()
	{
		$this->_db = Yii::app()->db;
		$this->_db->setAttribute(PDO::ATTR_CASE,PDO::CASE_LOWER);
	}
	
	public static function getInstance() 
    {
        if (null === self::$_instance) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }
	
	
	public function getList(array $args = array(), $intPage = 1, $intLimit = MIN_ROWS_PER_PAGE)
	{
		try{
			$defaults = array(		
			);
			$args = array_merge($defaults, $args);
			
			$intStart = ($intPage-1)*$intLimit;
			
			$cmd = $this->_db->createCommand('SELECT SQL_CALC_FOUND_ROWS role_id, role_name, role_description, role_is_default FROM tbl_roles');
			
			$arrResults = $cmd->queryAll();
			if(!empty($arrResults)){
				$arrResults[0]['total_rows'] = $this->_db->createCommand('SELECT FOUND_ROWS();')->queryScalar();
			}
			return $arrResults;
		} catch(Exception $ex){
			throw new Exception($ex->getMessage());
		}
	}
	
	public function get($id)
	{
		try{
			$strSQL = " SELECT role_id, role_name, role_description, role_is_default
						FROM tbl_roles
						WHERE role_id=:id";
			$cmd = $this->_db->createCommand($strSQL);
			$cmd->bindParam(":id",$id,PDO::PARAM_STR);
			return $arrResults = $cmd->queryRow();
		} catch(Exception $ex){
			throw new Exception($ex->getMessage());
		}
	}
	
	public function insert(array $args)
	{		
		try{
			$defaults = array(
				'role_name' => null,
				'role_description' => null,
				'role_is_default' => 0	
			);
			$args = array_merge($defaults, $args);
			
			$cmd = $this->_db->createCommand();
			$cmd->insert('tbl_roles',$args);
			return Yii::app()->db->getLastInsertId();
		} catch(Exception $ex){
			throw new Exception($ex->getMessage());
		}
	}
	
	public function update($id, array $args)
	{		
		try{
			$defaults = array(
				'role_name' => null,
				'role_description' => null,
				'role_is_default' => 0		
			);
			$args = array_merge($defaults, $args);
			
			$cmd = $this->_db->createCommand();
			return $cmd->update('tbl_roles',$args, 'role_id=:id', array(':id'=>$id));
		} catch(Exception $ex){
			throw new Exception($ex->getMessage());
		}
	}
	
	public function delete($id){
		try{
			//remove user in role
			$cmd = $this->_db->createCommand();
			$cmd->delete('tbl_users_roles', 'role_id=:id', array(':id'=>$id));
			//delete role
			$cmd = $this->_db->createCommand();
			return $cmd->delete('tbl_roles', 'role_id=:id', array(':id'=>$id));			
		} catch(Exception $ex){
			throw new Exception($ex->getMessage());
		}
	}
}